// Copyright 2008 Thiago H. de Paula Figueiredo
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package br.com.arsmachina.module.service.internal;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.hibernate.SessionFactory;
import org.hibernate.metadata.ClassMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import br.com.arsmachina.module.service.PrimaryKeyTypeService;

/**
 * {@link PrimaryKeyTypeService} implementation using Hibernate. 
 * 
 * @author Thiago H. de Paula Figueiredo
 */
public class HibernatePrimaryKeyTypeService implements PrimaryKeyTypeService {

	private static final Logger LOGGER = LoggerFactory.getLogger(HibernatePrimaryKeyTypeService.class);

	final private SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	final private Map<Class, Class> entityToPrimaryKeyTypeMap = new HashMap<Class, Class>();

	@SuppressWarnings("unchecked")
	final private Map<Class, String> entityToPrimaryKeyPropertyNameMap = new HashMap<Class, String>();

	/**
	 * Single constructor of this class.
	 * 
	 * @param sessionFactory a {@link SessionFactory}. It cannot be null.
	 */
	public HibernatePrimaryKeyTypeService(SessionFactory sessionFactory) {
		
		if (sessionFactory == null) {
			throw new IllegalArgumentException("Parameter sessionFactory cannot be null");
		}
		
		this.sessionFactory = sessionFactory;
		
	}

	@SuppressWarnings("unchecked")
	public Class getPrimaryKeyType(Class entityClass) {

		Class clasz = entityToPrimaryKeyTypeMap.get(entityClass);

		if (clasz == null) {

			final String primaryKeyPropertyName = getPrimaryKeyPropertyName(entityClass);
			final char firstChar = Character.toUpperCase(primaryKeyPropertyName.charAt(0));
			final String getterName = "get" + firstChar + primaryKeyPropertyName.substring(1);

			try {

				Method getter = entityClass.getMethod(getterName);
				clasz = getter.getReturnType();

			}
			catch (SecurityException e) {
				throw new RuntimeException(e);
			}
			catch (NoSuchMethodException e) {

				if (LOGGER.isWarnEnabled()) {

					LOGGER.warn(String.format("Primary key getter %s not found for class ",
							getterName, entityClass.getName()));

				}

			}

			entityToPrimaryKeyTypeMap.put(entityClass, clasz);

		}

		return clasz;

	}

	@SuppressWarnings("unchecked")
	public String getPrimaryKeyPropertyName(Class entityClass) {

		String name = entityToPrimaryKeyPropertyNameMap.get(entityClass);

		if (name == null) {

			final ClassMetadata classMetadata = sessionFactory.getClassMetadata(entityClass);
			
			if (classMetadata != null) {
				name = classMetadata.getIdentifierPropertyName();
				entityToPrimaryKeyPropertyNameMap.put(entityClass, name);
			}
			
		}
		
		return name;
		
	}

}
